<?php

use Biz\model\bigData\BrandWeeklyReport;
use Biz\model\brand\Brand as mBrand;
use Doraemon\model\Position\PositionRules;
use Doraemon\model\Task\TaskGroup as mTaskGroup;
use Doraemon\model\Task\UserTaskInfo as mUserTaskInfo;
use Doraemon\service\position\PositionApi;
use Doraemon\service\Task\Task;
use Doraemon\tools\ImgUrl;

/**
 * 品牌周报
 * Class WeeklyAction
 */
class WeeklyAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;

    /**
     * @throws \Exception
     */
    public function main()
    {
        $uid = $this->uid;
        $brandId = $this->getRequest()->getQuery('brand_id', 0);
        $weeklyDay = $this->getRequest()->getQuery('weekly_day', 0);
        if (empty($weeklyDay)) {
            $weeklyDay = BrandWeeklyReport::getWeeklyDay();
        }
        if (!empty($brandId)) {
            $uid = mBrand::getBrandUidById($brandId);
            $uid = empty($uid) ? 0 : $uid;
        }
        if (empty($brandId) && !empty($uid)) {
            $brandId = mBrand::getBrandIdByUid($uid);
        }
        $reportInfo = (!empty($brandId) && !empty($weeklyDay)) ? BrandWeeklyReport::get('*', ['brand_id' => $brandId, 'day' => $weeklyDay]) : [];
        $data = [];
        if ($reportInfo) {
            $isV2 = in_array($uid, [11162567, 5204019, 311930, 684080, 462361, 163932, 99418, 12019, 23300, 14625]) ? true : false;
            $report = [
                'brand_id' => $reportInfo['brand_id'],//品牌id
                'total_exp' => $isV2 ? $reportInfo['total_exp_v2'] : $reportInfo['total_exp_v1'],//本周曝光-曝光数
                'content_exp' => $isV2 ? $reportInfo['content_exp_v2'] : $reportInfo['content_exp_v1'],//本周曝光-内容曝光数
                'user_exp_per' => $isV2 ? $reportInfo['user_exp_per_v2'] : $reportInfo['user_exp_per_v1'],// 本周曝光-住友说曝光占比
                'wiki_exp' => $isV2 ? $reportInfo['wiki_exp_v2'] : $reportInfo['wiki_exp_v1'],//本周曝光-wiki曝光数
                'wiki_pv' => $reportInfo['wiki_pv'],// 本周曝光-wiki商品访问数
                'rank' => $reportInfo['rank'],// 本周曝光-排名（百分比）
                'new_fans' => $reportInfo['new_fans'], //本周涨粉-新增粉丝数
                'total_fans' => $reportInfo['total_fans'],  //本周涨粉-累计粉丝数
                'fans_diff' => $reportInfo['fans_diff'],// 本周涨粉-新增粉丝数-相比上周增长值
                'login_cnt' => $reportInfo['login_cnt'],//本周活跃-登陆天数
                'pub_cnt' => $reportInfo['pub_cnt'], //本周活跃-发布内容数
                'interact_cnt' => $reportInfo['interact_cnt'],  //本周活跃-互动数
                'obj_relate_cnt' => $reportInfo['obj_relate_cnt'],  //本周活跃-手动关联商品数
                'claim_content_cnt' => $reportInfo['claim_content_cnt'],  //本周活跃-手动收录内容数
                'to_claim_cnt' => $reportInfo['to_claim_cnt'],  //本周活跃-待认领内容数
                'to_claim_show' => $reportInfo['to_claim_show'],  //本周活跃-待认领内容对应总曝光数
            ];
            $data = [
                'weekly_start' => date('Y.m.d', strtotime('-6 days', strtotime($weeklyDay))),
                'weekly_end' => date('Y.m.d', strtotime($weeklyDay)),
                'report' => $report,
                'task' => $this->getLastWeekTask($uid),
                'activity' => [
                    [
                        'cover_img' => 'https://img.haohaozhu.cn/Op-imageShow/0095e30ku04q0EM00qud4wp?iv=1',
                        'link' => 'https://form.haohaozhu.cn/form/3e5d16ca9a84428a9cb9cdb6ca168ddf'//新品速递链接
                    ],
                    [
                        'cover_img' => 'https://img.haohaozhu.cn/Op-imageShow/2f93130ku04q0tu00qud4xb?iv=1',
                        'link' => 'https://form.haohaozhu.cn/form/f3f0c321b83c46fc9f6307ab12bae9b9'//好物轻测链接
                    ],
                    [
                        'cover_img' => 'https://img.haohaozhu.cn/Op-imageShow/80c4e30ku04q0I000qud4xx?iv=1',
                        'link' => 'https://form.haohaozhu.cn/form/0fadb9e9d5c24e45a799025306f32f58'//超级盲盒链接
                    ],
                    [
                        'cover_img' => 'https://img.haohaozhu.cn/Op-imageShow/8505630ku04q0B400qud4yi?iv=1',
                        'link' => 'https://form.haohaozhu.cn/form/587a8154ef5e415791aa13314ea696e2',//打榜活动
                    ],
                ]
            ];
        }
        $this->setSuccess($data);
    }


    private function getLastWeekTask($uid)
    {
        $result = [];
        $list = Task::getBrandLastWeekTaskList($uid);
        if ($list) {
            $info = array_shift($list);
            $result['group_info'] = $info['group_info'];
            $result['finished_new_user'] = 1;
            $result['task_list'] = [];
            foreach ($info['task_list'] as $row) {
                $taskShow = $this->getTaskShow($row);
                $row['show_title'] = $taskShow['show_title'];
                $row['show_icon'] = $taskShow['show_icon'];
                if (isset($row['link_type'])) {
                    unset($row['link_type']);
                }
                if (isset($row['link_params'])) {
                    unset($row['link_params']);
                }
                if (isset($row['link'])) {
                    unset($row['link']);
                }
                $result['task_list'][] = $row;
            }
        }
        if ($result) {
            if ($result['group_info']['group_state'] == mUserTaskInfo::TASK_STATE_FINISHED || $result['group_info']['finished_num'] > 0) {
                $result['finished_new_user'] = 1;
            } else {
                $result['finished_new_user'] = $this->isFinishedNewUserTask($uid);
            }
        }
        return $result;
    }

    private function getTaskShow($taskInfo)
    {
        $result = ['show_icon' => '', 'show_title' => ''];
        $operateNum = $taskInfo['operate_num'];
        switch ($taskInfo['id']) {
            case 20:
            case 25:
                $result['show_title'] = ['点赞', $operateNum, '条住友内容'];
                $picId = ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) ? 'bff7c303c03c0tV00qudawl' : '77854303c03c0EZ00qudamp';
                $result['show_icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $picId, ImgUrl::IMAGE_SIZE_OP_ORI);
                break;
            case 21:
            case 26:
                $result['show_title'] = ['评论', $operateNum, '条住友内容'];
                $picId = ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) ? '5a261303c03c0JP00qudaxl' : '120c5303c03c0Rb00qudax3';
                $result['show_icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $picId, ImgUrl::IMAGE_SIZE_OP_ORI);
                break;
            case 27:
                $result['show_title'] = ['精选', $operateNum, '条住友内容'];
                $picId = ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) ? 'e83af303c03c0oj00qudayh' : '8a44c303c03c0BZ00quday3';
                $result['show_icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $picId, ImgUrl::IMAGE_SIZE_OP_ORI);
                break;
            case 22:
            case 28:
                $result['show_title'] = ['引导住友发布', $operateNum, '条带品牌商品的内容'];
                $picId = ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) ? '7b589303c03c04O00qudazc' : 'fede1303c03c0FZ00qudayx';
                $result['show_icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $picId, ImgUrl::IMAGE_SIZE_OP_ORI);
                break;
            case 23:
            case 29:
                $result['show_title'] = ['认领', $operateNum, '条住友内容'];
                $picId = ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) ? 'ca0e1303c03c0HD00qudbbf' : 'fa1f0303c03c0L500qudbay';
                $result['show_icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $picId, ImgUrl::IMAGE_SIZE_OP_ORI);
                break;
            case 24:
            case 30:
                $result['show_title'] = ['为', $operateNum, '条住友内容关联商品'];
                $picId = ($taskInfo['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) ? '48d9c303c03c00a00qudb0f' : '10711303c03c07s00qudazv';
                $result['show_icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $picId, ImgUrl::IMAGE_SIZE_OP_ORI);
                break;
        }
        return $result;
    }

    private function isFinishedNewUserTask($uid)
    {
        $result = true;
        $time = time();
        $where = [
            'cycle' => mTaskGroup::CYCLE_TYPE_ONCE,
            'channel' => mTaskGroup::CHANNEL_BRAND_SERVICE,
            'start_time[<=]' => $time,
            'end_time[>=]' => $time,
            'group_status[!]' => mTaskGroup::GROUP_STATUS_DEL,
        ];
        $list = mTaskGroup::selectList($where);
        $groupIds = array_column($list, 'id');
        $groupList = array_column($list, null, 'id');
        $groupInfo = [];
        if ($groupIds) {
            //查询用户分群，过滤不符合条件的任务分组
            $hits = PositionApi::hitRules(PositionRules::MODULE_TYPE_TASK_GROUP, $groupIds, $uid);
            foreach ($groupIds as $groupId) {
                if ($hits[$groupId]) {
                    $groupInfo = $groupList[$groupId];
                }
            }
        }
        if ($groupInfo) {
            $taskTime = Task::getGroupTaskTime($groupInfo);
            $userGroupInfo = mUserTaskInfo::getUserTaskGroupInfo($uid, $groupInfo['id'], $taskTime);
            $result = ($userGroupInfo && $userGroupInfo['task_state'] == mUserTaskInfo::TASK_STATE_FINISHED) ? true : false;
        }
        return (int)$result;
    }
}